<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\service\EngineerService;
use think\Db;
use Carbon\Carbon;
use app\api\validate\User as UserValidate;
use think\Exception;

/**
 * 员工控制器
 * @package app\index\controller
 */
class Users extends Auth
{
    public $noNeedLogin = [
        //"*"
    ];

    /**
     * 获取会员列表
     */
    public function lists(){
        if ($this->request->isPost()) {
            $limit = $this->request->post('limit');
            $getData = $this->request->post();
            if(!isset($limit) || empty($limit)){
                $limit = '10';
            }
            //dump($this->userInfo);die;
            //楼面端用户
            if($getData['type'] == '1'){
                $data = Db::name('qt_users')
                    ->field('u.id,u.real_name,u.avatar,u.phone,r.name as role_name,u.status,u.work_number,t.title as work_type_name')
                    ->alias('u')
                    ->leftJoin('qt_user_role r','u.post_id = r.id')
                    ->leftJoin('qt_work_type t','u.top_type_id = t.id')
                    ->where(['u.store_id'=>$this->userInfo['store_id'],'u.group'=>'2'])
                    ->paginate($limit)->each(function ($item){
                        $item['avatar'] = get_img_path($item['avatar']);
                        return $item;
                    });
            }
            //技师
            if($getData['type'] == '2'){
                $data = Db::name('qt_users')
                    ->field('u.id,u.real_name,u.avatar,u.phone,r.name as role_name,u.status,u.work_number,t.title as work_type_name')
                    ->alias('u')
                    ->leftJoin('qt_user_role r','u.role = r.id')
                    ->leftJoin('qt_work_type t','u.top_type_id = t.id')
                    ->where(['u.store_id'=>$this->userInfo['store_id'],'u.group'=>'1'])
                    ->paginate($limit)->each(function ($item){
                        $item['avatar'] = get_img_path($item['avatar']);
                        return $item;
                    });
            }
            $this->result('获取成功',$data,200);
        }else{
            $this->result('请求错误','',204);
        }
    }

    /**
     * 用户信息详情
     */
    public function detail(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $data = Db::name('qt_users')
                ->alias('u')
                ->leftJoin('qt_user_role r','r.id = u.role')
                ->leftJoin('qt_work_type t','u.type_id = t.id')
                ->field('u.id,u.phone,u.work_number,u.sex,u.real_name,
                u.work_time,u.card,r.name,t.title as work_type_name,u.status,
                u.operation,u.card_no')
                ->where('u.id',$getData['user_id'])
                ->find();
            $data['user_project'] = Db::name('qt_user_project')
                ->where('engineer_id',$getData['user_id'])
                ->column('project_id');
            $this->result('获取成功',$data,200);
        }
    }


    /**
     * 用户信息详情
     */
    public function save(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new UserValidate();
            if (!$validate->scene('add_save')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $update = Db::name('qt_users')->where('id',$getData['user_id'])->update($getData);
            if($update !== false){
                $this->result('更新成功','',200);
            }
            $this->result('更新失败','',204);
        }
        $this->result('无效的请求','',204);
    }


    /**
     * 一件启用用户
     */
    public function enable(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['ids'])){
                $this->result('缺少参数','',204);
            }
            $userIds = explode(',',$getData['ids']);

            foreach ($userIds as $key=>$value){

                Db::name('qt_users')->where('id',$value)->update(['status'=>0]);
            }
            $this->result('启用成功','',200);
        }
        $this->result('请求错误','',204);
    }


    /**
     * 一件禁用用户
     */
    public function disable(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['ids'])){
                $this->result('缺少参数','',204);
            }
            $userIds = explode(',',$getData['ids']);
            foreach ($userIds as $key=>$value){
                Db::name('qt_users')->where('id',$value)->update(['status'=>1]);
            }
            $this->result('禁用成功','',200);
        }
        $this->result('请求错误','',204);
    }


    /**
     * 添加技师
     */
    public function addEngineer()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \think\Validate();
            if (!$validate->scene('add_engineer')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            //判断技师号好是否存在
            $find = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'group'=>'1','work_number'=>$getData['work_number']])->find();
            if(!empty($find)){
                $this->result('工号已经存在请修改工号', '', 204);
            }

            $find = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'group'=>'1','phone'=>$getData['phone']])->find();
            if(!empty($find)){
                $this->result('手机号已经存在', '', 204);
            }

            try {
                Db::startTrans();
                //处理数据
                $insertData['store_id'] = $this->userInfo['store_id'];
                $insertData['phone'] = $getData['phone'];
                $insertData['work_number'] = $getData['work_number'];
                $insertData['real_name'] = $getData['real_name'];
                $insertData['sex'] = $getData['sex']??0;
                $insertData['age'] = $getData['age']??0;
                $insertData['type_id'] = $getData['type_id'];
                $insertData['top_type_id'] = Db::name('qt_work_type')->where('id', $getData['type_id'])->value('pid');
                $insertData['work_time'] = strtotime($getData['work_time']) ?? null;
                $insertData['overtime'] = $getData['overtime'] ?? 0;
                $insertData['group'] = $getData['group_id'];
                $insertData['create_time'] = time();
                $insertData['content'] = $getData['content'] ?? '';
                $insertData['add_clock_project'] = $getData['add_clock_project'] ?? 0;
                $insertData['show_wechat'] = $getData['show_wechat'] ?? 0;
                $insertData['update_project_role'] = $getData['update_project_role'] ?? 0;
                $insertData['hand_code'] = $getData['hand_code'] ?? 0;

                //插入用户数据，并返回用户ID
                $userId = Db::name('qt_users')->insertGetId($insertData);

                //插入权限
                $auth['engineer_id'] = $userId;
                $auth['is_open'] = $getData['is_open']??0;
                $auth['is_recharge'] = $getData['is_recharge']??0;
                $auth['is_pay'] = $getData['is_pay']??0;
                $auth['is_retreat'] = $getData['is_retreat']??0;
                $auth['is_room'] = $getData['is_room']??0;
                $auth['is_hand_card'] = $getData['is_hand_card']??0;
                $auth['is_room_content'] = $getData['is_room_content']??0;
                Db::name('qt_users_auth')->insert($auth);

                //插入技师服务项目
                $projectIDs = explode(',', $getData['project_ids']);
                foreach ($projectIDs as $key => $value) {
                    $insert[$key]['engineer_id'] = $userId;
                    $insert[$key]['project_id'] = $value;
                    $insert[$key]['create_time'] = time();
                }
                Db::name('qt_user_project')->insertAll($insert);
                //更新用户门店记录
                $storeLog = Db::name('qt_user_store')->where(['user_id'=>$userId,'store_id'=>$this->userInfo['store_id']])->find();
                if(!empty($storeLog)){
                    Db::name('qt_user_store')->insert(['user_id'=>$userId,'store_id'=>$this->userInfo['store_id']]);
                }
                //更新用户信息
                $up['ivt_code'] = $userId;
                $up['login_token'] = token_rand();
                $up['password'] = pwd('123456',$userId);
                \app\common\model\Users::where(['id' => $userId])->update($up);

                //根据手牌编号更新手牌表员工ID
                if (!empty($getData['hand_code'])) {
                    EngineerService::updateHandCard($getData['hand_code'],$userId);
                }

                //写技师房列表
                $max_sort = Db::name('qt_order_queue')->where(['store_id'=>$this->userInfo['store_id']])->lock(true)->max('sort');
                Db::name('qt_order_queue')->insert([
                    'store_id'=>$this->userInfo['store_id'],
                    'user_id'=>$userId,
                    'created_time'=>time(),
                    'sort'=>$max_sort+1,
                ]);

                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('添加失败'.$exception->getMessage(), '', 204);
            }
            $this->result('添加成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 编辑技师技师
     */
    public function editEngineer()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new UserValidate();
            if (!$validate->scene('edit_engineer')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            try {
                Db::startTrans();
                //处理数据
                $insertData['id'] = $getData['id'];
                $insertData['phone'] = $getData['phone'];
                $insertData['work_number'] = $getData['work_number'];
                $insertData['real_name'] = $getData['real_name'];
                $insertData['sex'] = $getData['sex']??0;
                $insertData['age'] = $getData['age']??0;
                $insertData['type_id'] = $getData['type_id'];
                $insertData['top_type_id'] = $getData['type_id'];
                $insertData['work_time'] = strtotime($getData['work_time']);
                $insertData['overtime'] = $getData['overtime'];
                $insertData['update_time'] = time();
                $insertData['add_clock_project'] = $getData['add_clock_project'] ?? 0;
                $insertData['show_wechat'] = $getData['show_wechat']??0;
                $insertData['update_project_role'] = $getData['update_project_role']??0;
                $insertData['group'] = $getData['group'];
                $insertData['content'] = $getData['content'] ?? '';
                $insertData['hand_card_neima'] = $getData['hand_code'] ?? '';
                //更新用户数据，并返回用户ID
                Db::name('qt_users')->where('id',$getData['id'])->update($insertData);
                $userId = $getData['id'];
                //插入权限
                $auth['engineer_id'] = $userId;
                $auth['is_open'] = $getData['is_open']??0;
                $auth['is_recharge'] = $getData['is_recharge']??0;
                $auth['is_pay'] = $getData['is_pay']??0;
                $auth['is_retreat'] = $getData['is_retreat']??0;
                $auth['is_room'] = $getData['is_room']??0;
                $auth['is_hand_card'] = $getData['is_hand_card']??0;
                $auth['is_room_content'] = $getData['is_room_content']??0;
                Db::name('qt_users_auth')->where('engineer_id', $userId)->delete();//先删除
                Db::name('qt_users_auth')->insert($auth);//新增
                //插入技师服务项目
                $projectIDs = explode(',', $getData['project_ids']);
                foreach ($projectIDs as $key => $value) {
                    $insert[$key]['engineer_id'] = $userId;
                    $insert[$key]['project_id'] = $value;
                    $insert[$key]['create_time'] = time();
                }

                Db::name('qt_user_project')->where('engineer_id', $userId)->delete();//先删除
                Db::name('qt_user_project')->insertAll($insert);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('修改失败'.$exception->getMessage(), '', 204);
            }
            //给技师排等位
            $projectIDs = explode(',', $getData['project_ids']);
            foreach ($projectIDs as $key => $value) {
                //安排等位
                $waitRes = Db::name('qt_wait')
                    ->where(['store_id'=>$this->userInfo['store_id'],'status'=>'1','project_id'=>$value,'delay_time'=>'0'])
                    ->order('is_first desc id desc')
                    ->select();
                if(!empty($waitRes)){
                    $orderProject = Db::name('qt_order_project')->where('id',$waitRes[0]['order_id'])->select();
                    $model = new \app\common\model\Order();
                    $model->calculation($waitRes[0]['room_id'],$waitRes[0]['project_id'],$waitRes[0]['sex'],'1',$orderProject);
                    Db::name('qt_wait')->where(['id'=>$waitRes[0]['id']])->update(['status'=>'2']);
                }
            }
            $this->result('修改成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取修改的技师
     */
    public function getUser()
    {

        if ($this->request->isPost()) {

            $post = $this->request->post();
            $engineer_id = $post['id'];

            $userInfo = $this->userInfo;
            $engineer_data = EngineerService::getEnineerById($engineer_id, $userInfo['store_id']);
            if (empty($engineer_data)) {
                $this->result('没有查询到对应ID的数据', '', 204);
            }
            $users_auth = Db::name('qt_users_auth')->field('is_open,is_recharge,is_pay,is_retreat,is_room,is_hand_card,is_room_content,is_replace')->where('engineer_id', $engineer_id)->find() ?? [
                    "is_open"=>0,
                    "is_recharge"=>0,
                    "is_pay"=>0,
                    "is_retreat"=>0,
                    "is_room"=>0,
                    "is_hand_card"=>0,
                    "is_room_content"=>0,
                    "is_replace"=>0
                ];
            $hand_code['hand_code'] = $engineer_data['hand_card_neima'];
            $project['project_ids'] = Db::name('qt_user_project')->where('engineer_id',$engineer_id)->column('project_id')??[];
            $engineer_data = array_merge($engineer_data,$users_auth,$hand_code,$project);
            $engineer_data['work_time'] = ST($engineer_data['work_time']);
            $this->result('请求成功', $engineer_data, 200);

        } else {

            $this->result('无效的请求', '', 204);
        }
    }

    /**
     * 添加楼面接口
     */
    public function addFloor(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \think\Validate();
            if (!$validate->scene('add_floor')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            //判断技师号好是否存在
            $find = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'group'=>'2','work_number'=>$getData['work_number']])->find();
            if(!empty($find)){
                $this->result('工号已经存在请修改工号', '', 204);
            }

            $find = Db::name('qt_users')->where(['store_id'=>$this->userInfo['store_id'],'group'=>'2','phone'=>$getData['phone']])->find();
            if(!empty($find)){
                $this->result('手机号已经存在', '', 204);
            }

            $insertData['work_number'] = $getData['work_number'];
            $insertData['real_name'] = $getData['real_name'];
            $insertData['sex'] = $getData['sex'];
            $insertData['post_id'] = $getData['post_id'];
            $insertData['role'] = $getData['post_id'];
            $insertData['phone'] = $getData['phone'];
            $insertData['card'] = $getData['card'];
            $insertData['work_time'] = strtotime($getData['work_time']);
            $insertData['select_report_time'] = $getData['select_report_time'];
            $insertData['select_list_time'] = $getData['select_list_time'];
            $insertData['operation'] = $getData['operation'];
            $insertData['create_time'] = time();
            $insertData['group'] = $getData['group_id'];
            $insertData['hand_card_neima'] = $getData['hand_code'];

            try{
                Db::startTrans();
                $userId = Db::name('qt_users')->insertGetId($insertData);
                //更新用户信息
                $up['ivt_code'] = $userId;
                $up['password'] = pwd('123456',$userId);
                $up['login_token'] = token_rand();
                Db::name('qt_users')->where(['id' => $userId])->update($up);
                //更新用户门店记录
                $storeLog = Db::name('qt_user_store')->where(['user_id'=>$userId,'store_id'=>$this->userInfo['store_id']])->find();
                if(!empty($storeLog)){
                    Db::name('qt_user_store')->insert(['user_id'=>$userId,'store_id'=>$this->userInfo['store_id']]);
                }
                //插入菜单权限
                EngineerService::insertUserMenuAuth($userId,$getData['post_id']);


                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('添加失败'.$exception->getMessage(),'',204);
            }
            $this->result('添加成功','',200);
        }
    }

    /**
     * 修改楼面接口
     */
    public function editFloor(){

        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new UserValidate();
            if (!$validate->scene('add_floor')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $userInfo = $this->userInfo;
            $engineer_data = EngineerService::getEnineerById($getData['id'], $userInfo['store_id']);
            if (empty($engineer_data)) {
                $this->result('没有查询到对应ID的数据', '', 204);
            }
            $insertData['work_number'] = $getData['work_number'];
            $insertData['real_name'] = $getData['real_name'];
            $insertData['sex'] = $getData['sex'];
            $insertData['post_id'] = $getData['post_id'];
            $insertData['role'] = $getData['post_id'];
            $insertData['phone'] = $getData['phone'];
            $insertData['card'] = $getData['card'];
            $insertData['work_time'] = strtotime($getData['work_time']);
            $insertData['hand_code'] = $getData['hand_code'];
            $insertData['id'] = $getData['id'];
            $insertData['group'] = $getData['group'];
            $insertData['hand_card_neima'] = $getData['hand_code'];
            try{
                Db::startTrans();
                //更新用户信息
                //$insertData['login_token'] = token_rand();
                Db::name('qt_users')->where(['id'=>$getData['id']])->update($insertData);
                //插入菜单权限
                EngineerService::insertUserMenuAuth($getData['id'],$getData['post_id']);

                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('修改失败'.$exception->getMessage(),'',204);
            }
            $this->result('修改成功','',200);
        }
    }

    /**
     * 获取用户角色
     */
    public function getRole(){
        if ($this->request->isPost()) {
            $data =Db::name('qt_user_role')->field('id,name')->where(['store_id'=>$this->userInfo['store_id']])->select();
            $this->result('查询成功', $data, 200);
        }
    }




}
